/*
Throttle related routines
*/

#include <p30F4011.h>
#include "settings.h"
#include "AC-Controller.h"
#include "globals.h"
#include "eeprom.h"

volatile unsigned int throttle_feedback = 0;	 //throttle raw after having been processed and manipulated
volatile unsigned int throttle_raw; // directly from ADC reading
volatile unsigned int throttle_average = 0;
int throttle_min_setting;
int throttle_max_setting;

volatile unsigned throttle_fault_counts = 0;

void ProcessThrottle() {

	if (use_hardware & EE_USE_POT_THROTTLE) {
		//seperating the two allows for monitoring the raw value and the processed value. This aids in
		//debugging and also prevents the interrupt from overwriting the value after we've processed it
            
                //And, now I've custom coded a simple like PID like filtering of the throttle values
                //this code takes like 200-300 steps to synchronize the throttle feedback value (the output)
                //with the throttle_raw (the input). 
                //this prevents large jumps in throttle which isn't good for anybody.
                //eventually it might be good to use real PID and/or allow for configurable
                //throttle ramp. Granted, 200-300 steps is not much. We're running this throttle code at 4Khz so
                //300 runs through is 300 / 4000 = 75ms. That's still pretty quick throttle response! Especially since
                //most of the change happens in the first 25-50 steps
                //nonetheless, this code is self regulating so really it should work fine.
                //The feedback is set to be ">> 6" or "/ 64" of the throttle_average. Tweaking that ratio will set the throttle
                //following speed. If user configuration is desired then this would be the value to let them change
                throttle_average += throttle_raw;
                throttle_average -= throttle_feedback;
                throttle_feedback = throttle_average >> 6;
		if (throttle_feedback > throttle_max_setting) // clamp it to allow some dead zone.
			throttle_feedback = throttle_max_setting;
		else if (throttle_feedback < throttle_min_setting)
			throttle_feedback = throttle_min_setting;
		throttle_feedback -= throttle_min_setting;
		// now throttle_feedback is in [0, max-min], I have determined 0 to be zero throttle too
		// now, 0 throttle is 0 and max throttle is (max-min)
		//the absolute maximum range of throttle_feedback is still [0, 1023] but it's
		//likely less range because of all the stuff above

		//now... we want the actual throttle to become [0,1023] no matter what happened above
		//so recondition it. This means multiply the above by 1024 and divide by the 
		//throttle range. This yields the correct range no matter what.
		throttle_feedback = (((long)throttle_feedback) << 10) / (long)((long)throttle_max_setting - (long)throttle_min_setting);			
	}
}



